package cn.wolfcode.springboot_producer._01_hello;

import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.common.message.MessageConst;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;

@RestController
public class HelloController {
    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    //同步发送
    @RequestMapping("/send")
    public String send(String msg,String tag){
        //构建消息
       /* MessageBuilder<String> builder = MessageBuilder.withPayload(msg);
        org.springframework.messaging.Message<String> message = builder.build();
        rocketMQTemplate.send("01-boot-hello",message);*/

       //topic:tag
        rocketMQTemplate.syncSend("01-boot-hello:"+tag,msg);
        return "消息发送成功";
    }
    //消息过滤
    @RequestMapping("/filter")
    public String filter(String msg,String tag,String age){
        //消息过滤封装到map集合中
        HashMap<String, Object> map = new HashMap<>();
        map.put("age",age);
        map.put("weight","180");
        map.put(MessageConst.PROPERTY_KEYS,"123");//key值

        //topic:tag
        rocketMQTemplate.convertAndSend("01-boot-hello:"+tag,msg,map);
        return "消息发送成功";
    }

    //异步发送
    @RequestMapping("/asyncSend")
    public String asyncSend(String msg){
        //构建消息

        rocketMQTemplate.asyncSend("01-boot-hello", msg, new SendCallback() {
            @Override
            public void onSuccess(SendResult sendResult) {
                System.out.println("发送成功");
            }

            @Override
            public void onException(Throwable throwable) {
                System.out.println("发送失败");
            }
        });
        return "消息发送成功";
    }
    //一次性发送
    @RequestMapping("/sendOneWay")
    public String sendOneWay(String msg){
        //构建消息
        rocketMQTemplate.sendOneWay("01-boot-hello",msg);
        return "消息发送成功";
    }
    //集群消息广播
    @RequestMapping("/sendMode")
    public String sendMode(String msg){
        //构建消息
        rocketMQTemplate.syncSend("boot-consumer-mode",msg);
        return "消息发送成功";
    }

    //延迟消息
    @RequestMapping("/sendDaley")
    public String sendDaley(String msg){
        //构建消息
        MessageBuilder<String> builder = MessageBuilder.withPayload(msg);
        org.springframework.messaging.Message<String> message = builder.build();
        rocketMQTemplate.syncSend("boot-send-daley",message,5000,3);
        return "消息发送成功";
    }


}
